package zhibi.wechat.mp.config.wx_cp.handler;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import zhibi.wechat.mp.config.build.TextBuilder;
import zhibi.wechat.mp.domain.User;
import zhibi.wechat.mp.service.UserService;

import java.util.Map;

/**
 * 关注处理
 */
@Component
public class SubscribeHandler extends AbstractHandler {

    @Autowired
    private UserService userService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) throws WxErrorException {
        this.logger.info("新关注用户 OPENID: " + wxMessage.getFromUser());
        // 获取微信用户基本信息
        WxMpUser userWxInfo = weixinService.getUserService()
                .userInfo(wxMessage.getFromUser(), null);
        if (userWxInfo != null) {
            User user = userService.selectByPrimaryKey(userWxInfo.getOpenId());
            if (null == user) {
                user = new User();
                BeanUtils.copyProperties(userWxInfo, user);
                userService.insertSelective(user);
            } else {
                user.setSubscribe(true);
                userService.updateByPrimaryKeySelective(user);
            }
        }
        try {
            return new TextBuilder().build("感谢关注", wxMessage, weixinService);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }
        return null;
    }
}
